package com.taotao.search.service.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.taotao.common.pojo.SearchItem;
import com.taotao.common.pojo.SearchResult;

@Repository
public class SearchDao {

	@Autowired
	private SolrServer solrServer;
	
	public SearchResult search(SolrQuery query) throws Exception{
		//执行 查询
		QueryResponse response = solrServer.query(query);
		//取结果集
		SolrDocumentList documentList = response.getResults();
		//存放结果集
		SearchResult result = new SearchResult();
		List<SearchItem> list = new ArrayList<>();
		//遍历结果集
		for (SolrDocument solrDocument : documentList) {
			SearchItem searchItem = new SearchItem();
			searchItem.setCategory_name((String) solrDocument.get("item_category_name"));
			searchItem.setId((Long) solrDocument.get("id"));
			searchItem.setImage((String) solrDocument.get("item_image"));
			
			//获取高亮
			String item_title = null;
			Map<String, Map<String, List<String>>> highlighting = response.getHighlighting();
			List<String> list2 = highlighting.get(solrDocument.get("id")).get("item_title");
			//判断list2是否为空
			if(list2 != null && list2.size() > 0){
				item_title = list2.get(0);
			}else{
				item_title = (String) solrDocument.get("item_title");
			}
			//设置
			searchItem.setTitle(item_title);
			
			searchItem.setPrice((Long) solrDocument.get("item_price"));
			
			list.add(searchItem);
		}
		//查询结果的总记录数
		result.setRecourdCount(documentList.getNumFound());
		//设置list
		result.setSearchItemList(list);
		
		return result;
	}
}
